package com.sparrow.android31_slidingpanelayout.helper;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wenquan on 16/6/16.
 */
public class QRCodeHelper {

    /**
     *需要导入Zxing包
     * @param context:上下文对象
     * @param content:内容可以为文字与链接
     * @param weight:宽度
     * @param imageView_slider_face:设置到ImageView控件的地方
     * @param resID:中间logo资源ID,当为0时,没有logo
     */
    public static void createQRCode(Context context, String content, int weight, ImageView imageView_slider_face, int resID) {

        QRCodeWriter write = new QRCodeWriter();

        Map<EncodeHintType,Object> map = new HashMap<>();
        map.put(EncodeHintType.CHARACTER_SET,"UTF-8");

        //3设置容错登记
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

        //设置矩阵对象
        try {
            BitMatrix matrix = write.encode(content, BarcodeFormat.QR_CODE,weight,weight,map);

            //设置一个空白的Bitmap对象
            Bitmap bm = Bitmap.createBitmap(weight,weight, Bitmap.Config.RGB_565);

            //往Bitmap中写入矩阵信息,如果该矩阵点中有数据,则放置黑色点,否则放置白色点
            for (int x = 0; x < weight; x++) {
                for (int y = 0; y < weight; y++) {

                    if (matrix.get(x,y)){
                        bm.setPixel(x,y, Color.BLACK);
                    }else {
                        bm.setPixel(x,y, Color.WHITE);
                    }

                }

            }
            //7往二维码正中心回执logo
            imageView_slider_face.setImageBitmap(bm);
            if (resID!=0){
                Bitmap bm_ic = BitmapFactory.decodeResource(context.getResources(),resID);
                Rect rect_ic = new Rect(0,0,bm_ic.getWidth(),bm.getHeight());
                //desition:目标
                Rect rect_dest = new Rect(weight*2/5,weight*2/5,weight*3/5,weight*3/5);

                new Canvas(bm).drawBitmap(bm_ic,rect_ic,rect_dest,null);


            }


        } catch (WriterException e) {
            e.printStackTrace();
        }

    }
}
